package com.suray.socket.core;

import com.suray.basic.wcs.utils.LoggerType;
import com.suray.basic.wcs.utils.LoggerUtil;
import com.suray.basic.wcs.utils.ModuleType;
import com.suray.socket.ISocketCreate;
import com.suray.socket.SocketInterface;
import com.suray.socket.type.SocketType;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class SocketInstance {

    protected static ISocketCreate socketCreate;

    protected static Map<NetAddress, SocketInterface> sockets = new HashMap<>();

    public static void put(NetAddress netAddress, SocketInterface socket) {
        sockets.put(netAddress, socket);
    }

    private static int socketId = 0;

    public static SocketInterface get(Integer id) {
        if (id == null) {
            LoggerUtil.info(ModuleType.SOCKET, LoggerType.WARN, id, null, "获取socket对象的id不能为空", SocketInstance.class);
            return null;
        }

        return sockets.get(id);
    }

    public static void initSocketCreate(ISocketCreate socketCreate) {
        SocketInstance.socketCreate = socketCreate;
    }

    public static SocketInterface getInstance(String ip, int port, SocketType socketType) {
        NetAddress netAddress = new NetAddress(ip, port);
//        return socketCreate.findSocket(netAddress);
        SocketInterface socketInterface = sockets.get(netAddress);
        if (socketInterface != null) {
            return socketInterface;
        }
        socketInterface = socketCreate.addSocket(socketId++, ip, port, socketType);
        sockets.put(netAddress, socketInterface);
        return socketInterface;
    }

    public static void CheckNetAddress(NetAddress netAddress) {
        socketCreate.checkNetAddress(new HashSet<>(sockets.values()), netAddress);
    }

    public static void deleteSocket(SocketInterface socket) {
        socketCreate.deleteSocket(sockets, socket);
    }
}
